package org.karn.example.content_provider;

import java.util.ArrayList;

import org.karn.example.content_provider.MyCursorAdapter.ViewHolder;

import android.content.Context;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;


public class MyListAdapter extends BaseAdapter {

    Context mContext;
    LayoutInflater inflater;

    ArrayList<bookmarItem> mRows;
    ArrayList<String> mFolders;

    public MyListAdapter (Context context, ArrayList<bookmarItem> rows, ArrayList<String> folders)
    {
        mContext = context;
        mRows = rows;
        mFolders = folders;
        inflater = LayoutInflater.from(mContext);
    }

    @Override
    public int getCount ( )
    {
        return mRows.size() + mFolders.size();
    }

    @Override
    public Object getItem (int position)
    {
        return position;
    }

    @Override
    public long getItemId (int position)
    {
        return position;
    }

    @Override
    public View getView (int position, View convertView, ViewGroup parent)
    {
        ViewHolder holder;
        if(convertView == null)
        {
            holder       = new ViewHolder();
            convertView  = inflater.inflate(R.layout.list_item, null);
            holder.title = (TextView) convertView.findViewById(R.id.titleTxt);
            holder.url   = (TextView) convertView.findViewById(R.id.urlTxt);
            holder.image = (ImageView) convertView.findViewById(R.id.image);

            convertView.setTag(holder);
        }
        else
        {
            holder = (ViewHolder) convertView.getTag();
        }

        if(position < mFolders.size())
        {
            holder.title.setText(mFolders.get(position));
            holder.image.setImageResource(R.drawable.folder_closed);
            holder.url.setText("");
        }
        else
        {
            holder.title.setText(mRows.get(position-mFolders.size()).title);
            holder.url.setText(mRows.get(position-mFolders.size()).url);
            if(!mRows.get(position-mFolders.size()).favicon.equals("-"))
            {
                byte[] favIconBuffer = Base64.decode(mRows.get(position-mFolders.size()).favicon, Base64.NO_WRAP);
                holder.image.setImageBitmap(BitmapFactory.decodeByteArray(
                        favIconBuffer,0, favIconBuffer.length));
            }
            else
            {
                holder.image.setImageResource(R.drawable.ic_launcher);
            }
        }

        return convertView;
    }

    class ViewHolder {
        TextView title, url;
        ImageView image;
    }

}
